package com.manager.system.service.impl;

import com.manager.common.dao.SuperDao;
import com.manager.common.utils.DateTools;
import com.manager.common.utils.ObjectUtils;
import com.manager.common.vo.PageVO;
import com.manager.model.System_Permission;
import com.manager.model.System_User;
import com.manager.system.service.PermissionService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class PermissionServiceImpl extends SuperDao implements PermissionService {

    /**
     * 获取所有权限数据
     */
    @Override
    @Transactional
    public PageVO getAllPermission(System_Permission model) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuffer hql = new StringBuffer();
        hql.append(" from System_Permission t where 1 = 1 ");
        if(StringUtils.isNotEmpty(model.getName())){
            hql.append(" and t.name like '%"+model.getName()+"%' ");
        }
        List<System_Permission> list = this.getList(hql.toString(), 0,0, " order by  sort desc ");
        int count = this.getListCount("select count(*) "+hql.toString(), "");
        int page = count % model.getLimit() == 0 ? count / model.getLimit() : count / model.getLimit() + 1;

        return PageVO.create(model.getStart(),page, ObjectUtils.getJSONArray(System_Permission.config, list));
    }

    /**
     * 获取权限tree数据
     */
    @Override
    @Transactional
    public JSONArray getPermissionJsonData(String type, String table_id) {
        List<JSONObject> listObj = new ArrayList<JSONObject>();
        String hql = " from System_Permission t ";
        List<System_Permission> list = this.getList(hql, 0, 0, "");
        String hqlData = "";
        List<Object[]> listData = new ArrayList<Object[]>();
        if("orga".equals(type)){
            hqlData = " from System_Permission t left join t.listop t2 where t2.sys_orga.table_id = '"+table_id+"' and t.startUsing = '1' ";
        }else if("role".equals(type)){
            hqlData = " from System_Permission t left join t.listrp t2 where t2.sys_role.table_id = '"+table_id+"' and t.startUsing = '1' ";
        }else if("user".equals(type)){
            hqlData = " from System_Permission t left join t.listup t2 where t2.sys_user.table_id = '"+table_id+"' and t.startUsing = '1' ";
        }
        if(StringUtils.isNotEmpty(hqlData)){
            listData = this.getList(hqlData, 0, 0, "");
        }
        if(list!=null&&list.size()>0){
            for (System_Permission perm : list) {
                JSONObject obj = new JSONObject();
                obj.put("id", perm.getId());
                obj.put("name", perm.getName());
                obj.put("pid", perm.getPid());
                obj.put("type", perm.getType());
                obj.put("using", perm.getStartUsing());
                if(listData!=null&&listData.size()>0){
                    for (Object[] objs : listData) {
                        System_Permission permission = (System_Permission) objs[0];
                        if(permission.getId().equals(perm.getId())){
                            obj.put("checked", true);
                        }
                    }
                }
                listObj.add(obj);
            }
        }

        return JSONArray.fromObject(listObj);
    }

    /**
     * 修改权限
     */
    @Override
    @Transactional
    public void updatePermission(System_Permission model) {
        System_Permission perm = (System_Permission) this.loadT(model, model.getId());
        perm.setName(model.getName());
        perm.setPid(model.getPid());
        perm.setStartUsing(model.getStartUsing());
        perm.setShowTime(DateTools.getCurrentDate());
        perm.setSort(model.getSort());
        perm.setIcon(model.getIcon());
        perm.setType(model.getType());
        perm.setPath(model.getPath());
        this.updateT(perm);
    }


    /**
     * 获取用户权限数据
     */
    @Override
    @Transactional
    public JSONObject getUserMenuJsonArr(System_User user) {
        JSONObject jsonObject = new JSONObject();
        JSONArray menuArray = new JSONArray();
        List<String> btnList = new ArrayList<>();

        String hql1 = "select t from System_Permission t left join t.listup t1 where t1.sys_user.id = '"+user.getId()+"' and t.startUsing = '1'";
        String hql2 = "select t from System_Permission t left join t.listrp t1 left join t1.sys_role t2 left join t2.listur t3 where t.startUsing = '1' and t3.sys_user.id = '"+user.getId()+"' and t.startUsing = '1' and t2.status = '1' ";
        String hql3 = "select t from System_Permission t left join t.listop t1 left join t1.sys_orga t2 left join t2.listuo t3 where  t.startUsing = '1' and t3.sys_user.id = '"+user.getId()+"' and t.startUsing = '1'";
        String hql4 = "select t from System_Permission t left join t.listrp t1 where  t1.sys_role.defaultStatus = 1 and t.startUsing = '1' and t1.sys_role.status = '1' ";

        List<System_Permission> list1 = this.getList(hql1, 0, 0, "");
        List<System_Permission> list2 = this.getList(hql2, 0, 0, "");
        List<System_Permission> list3 = this.getList(hql3, 0, 0, "");
        List<System_Permission> list4 = this.getList(hql4, 0, 0, "");

        Set<System_Permission> set = new HashSet<System_Permission>(); //去掉重复
        //合并list1，list2，结果为list1
        if(list1!=null&&list1.size()>0){
            for (System_Permission system_Permission : list1) {
                set.add(system_Permission);
            }
        }
        if(list2!=null&&list2.size()>0){
            for (System_Permission system_Permission : list2) {
                set.add(system_Permission);
            }
        }
        if(list3!=null&&list3.size()>0){
            for (System_Permission system_Permission : list3) {
                set.add(system_Permission);
            }
        }

        if(list4 != null && list4.size() > 0){
            set.addAll(list4);
        }


        List<System_Permission> list = new ArrayList<System_Permission>(set);
        if(list!=null&&list.size()>0){
            Collections.sort(list, new Comparator<System_Permission>() {//根据sort排序
                @Override
                public int compare(System_Permission o1, System_Permission o2) {

                    return o1.getSort() - o2.getSort();
                }
            });

            for (System_Permission perm : list) {
                if("1".equals(perm.getType())){
                    JSONObject js = new JSONObject();
                    js.put("id", perm.getId());
                    js.put("text",perm.getName());
                    js.put("path",perm.getPath());
                    js.put("icon", perm.getIcon());
                    js.put("pId",perm.getPid());
                    js.put("type",perm.getType());
                    menuArray.add(js);
                    continue;
                }
                btnList.add(perm.getPath());
            }
        }
        jsonObject.put("menuData", menuArray);
        jsonObject.put("btnData", btnList);
        return jsonObject;
    }

    /**
     * 获取所有权限数据
     */
    @Override
    @Transactional
    public JSONObject getAdminMenuJsonArr() {
        JSONObject jsonObject = new JSONObject();
        JSONArray menuArray = new JSONArray();
        List<String> btnList = new ArrayList<>();
        JSONArray json = new JSONArray();
        String hql =" from System_Permission t where t.startUsing = '1' ";
        List<System_Permission> list = this.getList(hql, 0, 0, "order by t.sort");
        if (list != null && list.size() > 0) {
            for (System_Permission perm : list) {
                if ("1".equals(perm.getType())) {
                    JSONObject js = new JSONObject();
                    js.put("id", perm.getId());
                    js.put("text",perm.getName());
                    js.put("path",perm.getPath());
                    js.put("icon", perm.getIcon());
                    js.put("pId",perm.getPid());
                    js.put("type",perm.getType());
                    menuArray.add(js);
                    continue;
                }
                btnList.add(perm.getPath());
            }
        }
        jsonObject.put("menuData", menuArray);
        jsonObject.put("btnData", btnList);
        return jsonObject;
    }

    /**
     * 获取所有btn数据
     */
    @Override
    @Transactional
    public JSONArray getAdminBtnJsonArr() {
        JSONArray json = new JSONArray();
        String hql =" from System_Permission t where t.type = 'button'";
        List<System_Permission> list = this.getList(hql, 0, 0, "");
        if (list != null && list.size() > 0) {
            for (System_Permission perm : list) {
                JSONObject js = new JSONObject();
                js.put("id", perm.getId());
                js.put("name",perm.getName());
                js.put("pId",perm.getPid());
                js.put("type",perm.getType());
                json.add(js);
            }
        }
        return json;
    }

    /**
     * 根据权限ids获取tree数据
     */
    @Override
    @Transactional
    public JSONArray getPermissionTreeData(String perms) {
        JSONArray listObj = new JSONArray();
        String[]  permArr = null;
        if(StringUtils.isNotEmpty(perms)){
            permArr = perms.split(",");
        }
        String hql = " from System_Permission t ";
        List<System_Permission> list = this.getList(hql, 0, 0, "");
        if (list != null && list.size() > 0) {
            for (System_Permission perm : list) {
                JSONObject obj = new JSONObject();
                obj.put("table_id", perm.getId());
                obj.put("cid", perm.getId());
                obj.put("name", perm.getName());
                obj.put("pid", perm.getPid());
                obj.put("type", perm.getType());
                obj.put("using", perm.getStartUsing());
                if (permArr != null && permArr.length > 0) {
                    for (String permId : permArr) {
                        if (perm.getId().equals(permId)) {
                            obj.put("checked", true);
                        }
                    }
                }
                listObj.add(obj);
            }
        }
        return listObj;
    }

    /**
     * 获取权限toolTip数据
     */
    @Override
    @Transactional
    public String getPermToolTipData(String perms) {
        String permTip = "";
        String[] permIds = null;
        if(StringUtils.isNotEmpty(perms)){
            permIds = perms.split(",");
        }
        if(permIds != null && permIds.length > 0){
            for(int i = 0;i<permIds.length;i++){
                System_Permission perm = (System_Permission) this.loadT(new System_Permission(), permIds[i]);
                permTip +=perm.getName();
                if(i != permIds.length - 1){
                    permTip +=",";
                }
            }
        }
        return permTip;
    }

    @Override
    @Transactional
    public void addPermission(System_Permission model) {
        model.setCreateTime(DateTools.getCurrentDateLong());
        model.setShowTime(DateTools.getCurrentDate());
        this.addT(model);
    }


    @Override
    @Transactional
    public System_Permission getPermissByEnName(String enName) {
        String hql = " from System_Permission t where t.url like ?";
        System_Permission model=(System_Permission) this.getListOne("select t "+hql, new String[] {"%"+enName}, "");
        return model;
    }


    @Override
    @Transactional
    public void deletePermission(System_Permission model) {
        System_Permission per=(System_Permission) this.loadT(model, model.getId());
        this.delete(per);
    }


    @Override
    @Transactional
    public void updatePermissionStatus(System_Permission model) {
        // TODO Auto-generated method stub
        System_Permission system_Permission = (System_Permission) this.getT(new System_Permission(), model.getId());
        system_Permission.setStartUsing("1".equals(model.getStartUsing()) ? "0" : "1");

        this.updateT(system_Permission);
    }

    @Override
    public List<System_Permission> getAllPermission() {
        String sql = " from System_Permission t ";
        List<System_Permission> list = this.getList(sql,0,0," order by t.sort ");
        return list;
    }
}
